package com.sduept.nwld.dataserver.controller.fault;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import javax.faces.bean.ManagedBean;
import javax.faces.view.ViewScoped;
import javax.inject.Named;

import org.apache.commons.lang3.StringUtils;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import org.primefaces.model.menu.DefaultMenuItem;
import org.primefaces.model.menu.DefaultMenuModel;
import org.primefaces.model.menu.DefaultSeparator;
import org.primefaces.model.menu.MenuModel;

import com.alibaba.fastjson.JSONArray;
import com.sduept.bigdata.fault.entity.FaultRecord;
import com.sduept.bigdata.fault.entity.FaultRecordAttachment;
import com.sduept.bigdata.fault.manager.FaultEditLockManager;
import com.sduept.bigdata.fault.manager.FaultManager;
import com.sduept.bigdata.fault.manager.FaultRecordAttachmentManager;
import com.sduept.bigdata.fault.manager.FaultRecordQueryManager;
import com.sduept.bigdata.fault.manager.FaultReportQueryManager;
import com.sduept.bigdata.fault.manager.WaveFileAssistManager;
import com.sduept.bigdata.fault.report.etl.factory.AnalysisModelFactoryBuilder;
import com.sduept.bigdata.fault.report.etl.model.DeviceActionDTO;
import com.sduept.bigdata.fault.report.etl.model.DeviceActionDetailDTO;
import com.sduept.bigdata.fault.report.etl.model.FaultDetailDTO;
import com.sduept.bigdata.fault.report.etl.model.LineFaultReportDTO;
import com.sduept.bigdata.fault.report.etl.model.ProtectionActionAnalysisModel;
import com.sduept.bigdata.fault.report.etl.model.ProtectionActionTimeAnalysisModel;
import com.sduept.cim.model.extend.AbstractWaveFile;
import com.sduept.cim.model.extend.WaveFile;
import com.sduept.cim.model.wires.BusbarSection;
import com.sduept.core.dao.SuperDAO;
import com.sduept.nwld.dataserver.manager.etl.ProtectionDeviceActionETLManager;
import com.sduept.nwld.dataserver.manager.fault.FaultRecordAttachmentAssistManager;
import com.sduept.permission.manager.PersonnelManager;
import com.sduept.utils.DateUtil;

//@ManagedBean
//@ViewScoped
@Named
@ViewScoped
public class BusFaultDetailsController extends ProtectActSvgController {

	private static final long serialVersionUID = 5951923080727301292L;
	@Autowired
	private SuperDAO dao;
	@Autowired
	private WaveFileAssistManager wfam;
	@Autowired
	private FaultManager faultManager;
	@Autowired
	private FaultRecordQueryManager queryManager;
	@Autowired
	private FaultReportQueryManager frqm;
	@Autowired
	private ProtectionDeviceActionETLManager actionETLManager;
	@Autowired
	private FaultRecordAttachmentAssistManager attachAssManager;
	@Autowired
	private FaultRecordAttachmentManager attachManager;
	@Autowired
	private FaultEditLockManager lockM;
	@Autowired
	private PersonnelManager personM;

	private ProtectionActionAnalysisModel pmodel;
	private FaultRecord record;
	private String faultTime = null;
	private String deviceId = null;
	private String faultId = null;
	private String actTimeList = null;
	private String showBackButton;
	private MenuModel firstWaveListModel;
	private List<AbstractWaveFile> firstWaveList;
	private StreamedContent file;
	private String startStationId = null;
	private String startStation = null;
	/**
	 * 第一个站的故障报告明细
	 */
	private LineFaultReportDTO firstSt;
	private List<DeviceActionDTO> firstActList = new ArrayList<DeviceActionDTO>();
	private List<FaultDetailDTO> currentList;
	private List<FaultDetailDTO> voltageList;
	private List<FaultDetailDTO> diffCurrentDetailList;
	private List<DeviceActionDetailDTO> sumFirstActDetailList = new ArrayList<DeviceActionDetailDTO>();
	ProtectionActionTimeAnalysisModel firstAction = new ProtectionActionTimeAnalysisModel();
	List<DeviceActionDetailDTO> firstActDetailList = new ArrayList<DeviceActionDetailDTO>();

	private List<FaultRecordAttachment> attachmentList = new ArrayList<>();

	/**
	 * 初始化故障信息
	 *
	 * 将FaultRecord查询由使用SuperDAO改为使用 FaultRecordQueryManager查询 （20190109 zhangqi）
	 */
	@PostConstruct
	public void init() {
		if (StringUtils.isBlank(deviceId)) {
			deviceId = getParameter("lineId");
		}
		if (StringUtils.isBlank(showBackButton)) {
			showBackButton = getParameter("showBackButton");
		}
		if (StringUtils.isEmpty(deviceId)) {
			return;
		}
		if (faultTime == null) {
			faultTime = getParameter("faultTime");
		}
		Date dateTime = DateUtil.getDateByString(faultTime, DateUtil.pattern_ymdhms);
		List<FaultRecord> findByCondition = queryManager.findEqFaultTimeFaultByTimeDeviceId(dateTime, deviceId);
		if (findByCondition.size() > 0) {
			record = findByCondition.get(0);
			faultId = record.getId();
		}
		try {
			pmodel = AnalysisModelFactoryBuilder.getAnalysisModelFactory(AnalysisModelFactoryBuilder.muxian)
					.makeAnalysisReport(deviceId, dateTime);
		} catch (Exception e) {
			e.printStackTrace();
		} // busManager.getBusFaultAnalysisReport(deviceId, dateTime);
		if (pmodel.getFirstActions() != null) {
			firstActList = pmodel.getFirstActions().getProtectionActionList();
			currentList = pmodel.getFirstSt().getFaultCurrentDetailList();// 电流
			voltageList = pmodel.getFirstSt().getFaultVoltageDetailList();// 电压
		}
		firstSt = pmodel.getFirstSt();
		diffCurrentDetailList = pmodel.getDiffCurrentDetailList();// 差动电流
		reloadSumActDetailList();
		// 组织时间序列图需要的数据
		actTimeList = getActTimeListStr();
		BusbarSection busBar = dao.findById(deviceId, BusbarSection.class);
		startStationId = busBar.getSubId();
		startStation = busBar.getSubName();
		if (pmodel.getFirstSt() != null) {
			firstWaveList = wfam.findWaveFileList(record, startStationId);
			firstWaveListModel = loadWaveListMenu(firstWaveList);
		}
		// 初始化附件图片
		attachmentList = attachManager.findByFaultId(faultId);
	}

	private void reloadSumActDetailList() {
		firstAction = pmodel.getFirstActions();
		if (null != firstAction) {
			firstActDetailList = firstAction.getProtectionActionDetailList();
		}
		sumFirstActDetailList.clear();
		if (firstActDetailList != null && firstActDetailList.size() > 0) {
			sumFirstActDetailList.addAll(firstActDetailList);
			if (pmodel.getFirstSt() != null) {
				DeviceActionDetailDTO sum1 = new DeviceActionDetailDTO();
				sum1.setProtectName("总出口");
				sum1.setProtectType(pmodel.getFirstSt().getTotalExportCount() + "次");
				sumFirstActDetailList.add(sum1);
			}
		}
	}

	public String replaceWithBr(String str) {
		if (StringUtils.isEmpty(str)) {
			str = "";
		} else {
			str = str.replaceAll("(\r\n|\r|\n|\n\r)", "<br/>");
		}
		return str;
	}

	public void reloadActionData() {
		actionETLManager.getAndSaveActionData(record);
		frqm.reloadDeviceDetailActionDTO(record.getId(), pmodel);
		firstActDetailList = pmodel.getFirstActions().getProtectionActionDetailList();
		if (firstActDetailList.size() > 0) {
			setActTimeList(getActTimeListStr());
		}
		reloadSumActDetailList();
	}

	private String getActTimeListStr() {
		JSONArray jsonArray = new JSONArray();
		com.alibaba.fastjson.JSONObject firstJso = null;
		if (null == pmodel.getFirstSt() || (firstAction.getProtectionActionList().size() == 0
				&& firstAction.getBreakerActionList().size() == 0)) {
			if (firstActDetailList.size() > 0) {
				// 如果没有录波文件的话,取动作元件的时间列表
				firstJso = getActListByComponent(pmodel.getFirstSt().getSubstationName(), firstActDetailList);
			}
		} else {
			firstJso = getActTimeListByRecorder(pmodel.getFirstSt().getSubstationName(), firstAction);
		}
		if (null != firstJso) {
			jsonArray.add(firstJso);
		}
		return jsonArray.toJSONString();
	}

	// 下载录波文件
	public void downLoadFile() {
		FileInputStream fis = null;
		try {
			fis = wfam.generateDownloadZipFile(record, startStationId);
			file = new DefaultStreamedContent(fis, "application/octet-stream", record.getEquipment() + ".zip");
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		}
		if (file == null) {
			addErrorMessage("查找文件失败，无法下载");
		}
	}

	private MenuModel loadWaveListMenu(List<AbstractWaveFile> waveList) {
		MenuModel waveListModel = new DefaultMenuModel();
		if (waveList.size() == 0) {
			DefaultMenuItem item = new DefaultMenuItem();
			item.setValue("无录波文件");
			waveListModel.addElement(item);
		} else {
			for (AbstractWaveFile w : waveList) {
				DefaultMenuItem item = new DefaultMenuItem();
				item.setIcon("ui-icon-folder-open");
				if (w instanceof WaveFile) {
					item.setValue("集中录波");
				} else {
					item.setValue(w.getEquipType());
				}
				item.setOnclick("openWaveDlg('" + w.getId() + "','" + startStationId + "','" + startStation + "')");
				waveListModel.addElement(item);
			}
			DefaultMenuItem item = new DefaultMenuItem();
			item.setIcon("ui-icon-arrowthick-1-s");
			item.setValue("下载全部录波文件");
			item.setUpdate("file");
			item.setOncomplete("document.getElementById('form1:file').click();");
			waveListModel.addElement(item);

		}
		waveListModel.addElement(new DefaultSeparator());
		DefaultMenuItem item = new DefaultMenuItem();
		item.setIcon("ui-icon-grip-dotted-vertical");
		item.setValue("查看故障特征");
		item.setOnclick("openHarDlg('" + pmodel.getFirstSt().getFaultFileId() + "')");
		waveListModel.addElement(item);
		return waveListModel;
	}

	public void forecast() {
		List<FaultRecord> frs = queryManager.findEqFaultTimeFaultByTimeDeviceId(pmodel.getFaultTime(),
				pmodel.getFaultLineId());
		if (frs.size() > 0) {
			FaultRecord fr = frs.get(0);
			faultManager.setupFaultForecastReasonClassify(fr, pmodel);
			pmodel.setFaultForecastReason(fr.getFaultForecastReson());
		}
	}

	public void downloadAttachment() {
		if (attachmentList != null && attachmentList.size() > 0) {
			file = attachAssManager.getAttachmentFile(attachmentList);
			if (file == null) {
				addErrorMessage("该文件不存在");
			}
		}
	}

	public boolean isPicture(FaultRecordAttachment m) {
		return attachAssManager.isPicture(m.getSuffix());
	}

	public String getVirtualPath(String path) {
		return attachAssManager.getFullPath(path);
	}

	public FaultRecord getRecord() {
		return record;
	}

	public void setRecord(FaultRecord record) {
		this.record = record;
	}

	public ProtectionActionAnalysisModel getPmodel() {
		return pmodel;
	}

	public void setPmodel(ProtectionActionAnalysisModel pmodel) {
		this.pmodel = pmodel;
	}

	public String getDeviceId() {
		return deviceId;
	}

	public void setDeviceId(String deviceId) {
		this.deviceId = deviceId;
	}

	public LineFaultReportDTO getFirstSt() {
		return firstSt;
	}

	public void setFirstSt(LineFaultReportDTO firstSt) {
		this.firstSt = firstSt;
	}

	public List<FaultDetailDTO> getCurrentList() {
		return currentList;
	}

	public void setCurrentList(List<FaultDetailDTO> currentList) {
		this.currentList = currentList;
	}

	public List<FaultDetailDTO> getVoltageList() {
		return voltageList;
	}

	public void setVoltageList(List<FaultDetailDTO> voltageList) {
		this.voltageList = voltageList;
	}

	public List<DeviceActionDTO> getFirstActList() {
		return firstActList;
	}

	public void setFirstActList(List<DeviceActionDTO> firstActList) {
		this.firstActList = firstActList;
	}

	public List<FaultDetailDTO> getDiffCurrentDetailList() {
		return diffCurrentDetailList;
	}

	public void setDiffCurrentDetailList(List<FaultDetailDTO> diffCurrentDetailList) {
		this.diffCurrentDetailList = diffCurrentDetailList;
	}

	public List<DeviceActionDetailDTO> getSumFirstActDetailList() {
		return sumFirstActDetailList;
	}

	public void setSumFirstActDetailList(List<DeviceActionDetailDTO> sumFirstActDetailList) {
		this.sumFirstActDetailList = sumFirstActDetailList;
	}

	public String getActTimeList() {
		return actTimeList;
	}

	public void setActTimeList(String actTimeList) {
		this.actTimeList = actTimeList;
	}

	public ProtectionActionTimeAnalysisModel getFirstAction() {
		return firstAction;
	}

	public void setFirstAction(ProtectionActionTimeAnalysisModel firstAction) {
		this.firstAction = firstAction;
	}

	public String getShowBackButton() {
		return showBackButton;
	}

	public void setShowBackButton(String showBackButton) {
		this.showBackButton = showBackButton;
	}

	public StreamedContent getFile() {
		return file;
	}

	public void setFile(StreamedContent file) {
		this.file = file;
	}

	public MenuModel getFirstWaveListModel() {
		return firstWaveListModel;
	}

	public void setFirstWaveListModel(MenuModel firstWaveListModel) {
		this.firstWaveListModel = firstWaveListModel;
	}

	public String getFaultId() {
		return faultId;
	}

	public void setFaultId(String faultId) {
		this.faultId = faultId;
	}

	public List<FaultRecordAttachment> getAttachmentList() {
		return attachmentList;
	}

	public void setAttachmentList(List<FaultRecordAttachment> attachmentList) {
		this.attachmentList = attachmentList;
	}

}
